public class PrintInOrder {
    public static boolean firstFinished,secondFinished; //分别标记第一、第二个线程是否执行完
    public static Object locker = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            synchronized (locker) {
                System.out.print("c");
                firstFinished = true;
                locker.notifyAll(); //全部唤醒是为了保证能唤醒 t2，让它能继续执行
            }
        });
        Thread t2 = new Thread(()->{
            synchronized (locker) {
                while (!firstFinished) {  //只要第一个线程还没完成，就等待
                    try {
                        locker.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.print("b");
                secondFinished = true;
                locker.notifyAll(); //全部唤醒是为了保证能唤醒 t3，让它能继续执行
            }
        });
        Thread t3 = new Thread(()->{
            synchronized (locker) {
                while(!secondFinished) {  //只要第二个线程还没完成，就等待
                    try {
                        locker.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.print("a");
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
